//
//  BaseWebVC.swift
//  H5 页面
//
//  Created by 千策万划-mini on 2025/4/30.
//

import Foundation
import StoreKit
import WebKit

class BaseWebVC: BaseTableVC, WKNavigationDelegate, WKScriptMessageHandler {

    private var navView: BaseNavView?
    private var startTime: String?
    var webUrl: String = ""
    var isPop: Bool = false
    var blockSwitchTabBarToHomePage: (() -> Void)?
    var blockShowLogin:(() -> Void)?

    // MARK: - lazy
    private lazy var userContentController: WKUserContentController = {
        let controller = WKUserContentController()
        controller.add(self, name: LOCAL_H5_SEND_EMAIL)
        controller.add(self, name: LOCAL_H5_PISK_BURY_POINT)
        controller.add(self, name: LOCAL_H5_TO_GRADE)
        controller.add(self, name: LOCAL_H5_CLOSE_CURRENT)
        controller.add(self, name: LOCAL_H5_AGAIN_ONE_ORDER)
        return controller
    }()

    private lazy var webView: WKWebView = {
        let configuration = WKWebViewConfiguration()
        let preferences = WKWebpagePreferences()
        preferences.allowsContentJavaScript = true
        configuration.defaultWebpagePreferences = preferences

        configuration.userContentController = userContentController

        let dataStore = WKWebsiteDataStore.default()
        configuration.websiteDataStore = dataStore

        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.frame = CGRect(x: 0,
                               y: NAVIGATIONBAR_HEIGHT + 5,
                               width: SCREEN_WIDTH,
                               height: SCREEN_HEIGHT - NAVIGATIONBAR_HEIGHT - 5)
        webView.scrollView.bounces = false
        webView.navigationDelegate = self
        edgesForExtendedLayout = []

        if let html = "\(webUrl)\(GlobalMethod.getCommonUrl())".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
            webView.load(URLRequest(url: URL(string: html)!))
        }
        return webView
    }()

    // MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        if webUrl.contains("?") {
            // 如果包含 ?，说明已经有参数了，用 & 拼接
            webUrl = webUrl + "&"
        } else {
            // 如果不包含 ?，说明还没有参数，用 ? 拼接
            webUrl = webUrl + "?"
        }
        startTime = GlobalMethod.getTimeStampMillisecond()
        LocationService.shared.startUpdatingLocation()
        setupNavigation()
        setupUI()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        userContentController.removeScriptMessageHandler(forName: LOCAL_H5_SEND_EMAIL)
        userContentController.removeScriptMessageHandler(forName: LOCAL_H5_PISK_BURY_POINT)
        userContentController.removeScriptMessageHandler(forName: LOCAL_H5_TO_GRADE)
        userContentController.removeScriptMessageHandler(forName: LOCAL_H5_CLOSE_CURRENT)
        userContentController.removeScriptMessageHandler(forName: LOCAL_H5_AGAIN_ONE_ORDER)
    }

    // MARK: - UI Setup
    private func setupNavigation() {
        navView = BaseNavView.initNavBackTitle(title: "", rightView: nil)
        navView?.blockBack = { [weak self] in
            guard let self = self else { return }
            if self.webView.canGoBack {
                self.webView.goBack()
            } else {
                if self.isPop {
                    GB_Nav?.popViewController(animated: true)
                } else {
                    GB_Nav?.popToRootViewController(animated: true)
                    if let block = blockShowLogin {
                        block()
                    }
                }
            }
        }
        if let navView = navView {
            view.addSubview(navView)
        }
    }

    private func setupUI() {
        view.backgroundColor = COLOR_BACKGROUND
        viewBg.backgroundColor = COLOR_BACKGROUND
        tableView.backgroundColor = .clear
        view.addSubview(webView)
    }

    // MARK: - WKNavigationDelegate
    func webView(_: WKWebView, didStartProvisionalNavigation _: WKNavigation!) {
        GlobalMethod.showLoadingView()
    }

    func webView(_ webView: WKWebView, didFinish _: WKNavigation!) {
        navView?.changeTitle(title: webView.title ?? "")
        GlobalMethod.hideLoadingView()
    }

    func webView(_: WKWebView, didFail _: WKNavigation!, withError _: Error) {
        GlobalMethod.hideLoadingView()
    }

    func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError _: Error) {
        GlobalMethod.hideLoadingView()
    }

    // MARK: - WKScriptMessageHandler
    func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
        print("返回结果了\(message.name)")
        print("返回结果了\(message.body)")

        switch message.name {
        case LOCAL_H5_SEND_EMAIL:
            handleEmail(message.body)
        case LOCAL_H5_PISK_BURY_POINT:
            handleRiskControl(message.body)
        case LOCAL_H5_TO_GRADE:
            requestAppReview()
        case LOCAL_H5_CLOSE_CURRENT:
            handleNavigation(message.body)
        case LOCAL_H5_AGAIN_ONE_ORDER:
            againOneOrder(message.body)
        default:
            break
        }
    }

    // MARK: - Helper Methods
    // 发送邮件
    private func handleEmail(_ body: Any) {
        var emailAddress = getEmailWith(body as? String ?? "")
        if emailAddress.isEmpty {
            emailAddress = body as? String ?? ""
        }

        let subject = ""
        let body = "APP Name：\(UnPackStr(GlobalMethod.getAppName()))\nPhone：\(GlobalData.sharedInstance.GB_UserModel?.cap ?? "")\nI need help："

        if let urlString = "mailto:\(emailAddress)?subject=\(subject)&body=\(body)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
           let url = URL(string: urlString)
        {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    // 再来一单
    private func againOneOrder(_ body: Any) {
        guard let bodyString = body as? String else { return }
        
        if bodyString.contains("http") {
            webUrl = bodyString
            if let html = "\(webUrl)\(GlobalMethod.getCommonUrl())".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                webView.load(URLRequest(url: URL(string: html)!))
            }
        } else {
            if bodyString.contains(LOCAL_PRODUCT_DETAIL_ROUTE) {
                // 产品详情 "quiet": "would://gasped.Hound.nothing/ashNinjaYam?carry=2"
                if let quietRange = bodyString.range(of: "?", options: .backwards) {
                    let quietPart = bodyString[quietRange.upperBound...]
                    let pairs = quietPart.components(separatedBy: "&")
                    for pair in pairs {
                        let components = pair.components(separatedBy: "=")
                        if components.first == "carry" && components.count > 1 {
                            let makeValue = components.last?.trimmingCharacters(in: .whitespaces) ?? ""
                            let vc = ProductDetailVC()
                            vc.productCode = makeValue
                            GB_Nav?.pushViewController(vc, animated: true)
                            break
                        }
                    }
                }
            }
        }
    }
    
    private func handleRiskControl(_ body: Any) {
        if let list = body as? [Any], let first = list.first {
            GlobalMethod.buryPoint(productCode: "\(first)",
                                   type: "10",
                                   startTime: GlobalMethod.getTimeStamp(),
                                   endTime: GlobalMethod.getTimeStamp()
            )
        }
    }

    private func handleNavigation(_ body: Any) {
        guard let bodyString = body as? String else { return }

        if bodyString.contains("http") {
            webUrl = bodyString
            if let html = "\(webUrl)\(GlobalMethod.getCommonUrl())".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                webView.load(URLRequest(url: URL(string: html)!))
            }
        } else {
            if bodyString.contains(LOCAL_H5_BACK_HOMEPAGE) {
                blockSwitchTabBarToHomePage?()
                GB_Nav?.popToRootViewController(animated: true)
            } else if bodyString.contains(LOCAL_PRODUCT_DETAIL_ROUTE) {
                let array = bodyString.components(separatedBy: "=")
                if let code = array.last {
                    let vc = ProductDetailVC()
                    vc.productCode = code
                    GB_Nav?.pushViewController(vc, animated: true)
                }
            }
        }
    }

    private func requestAppReview() {
        if #available(iOS 14.0, *) {
            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                SKStoreReviewController.requestReview(in: windowScene)
            } else {
                print("No active window scene found")
            }
        } else {
            SKStoreReviewController.requestReview()
        }
    }

    private func getEmailWith(_ originalString: String) -> String {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
            if let match = regex.firstMatch(in: originalString,
                                            range: NSRange(location: 0, length: originalString.utf16.count))
            {
                let email = (originalString as NSString).substring(with: match.range)
                print("提取的邮箱：\(email)")
                return email
            }
        } catch {
            print("正则表达式错误：\(error)")
        }
        return ""
    }
}
